package cn.bugstack.springframework.beans;

import java.lang.reflect.Field;

/**
 * @author: yulong
 * @date: 2021/8/11
 */
public class BeanUtils {


    public static void setFieldValue(Object bean, String name, Object value) throws  BeansException {
        if (bean == null) {
            throw new BeansException("bean can not be null");
        }
        Class<?> aClass = bean.getClass();
        try {
            Class<?> superclass = aClass.getSuperclass();
            if (superclass != null) {
                Field[] declaredFields = superclass.getDeclaredFields();
                for (Field i : declaredFields) {
                    i.setAccessible(true);
                    if (name.equalsIgnoreCase(i.getName())) {

                        Class<?> type = i.getType();
                        if("java.lang.Integer".equalsIgnoreCase(type.getName())){
                            String s = String.valueOf(value);
                            int mvalue = Integer.valueOf(s);
                            i.set(bean, mvalue);
                        }else{
                            i.set(bean, value);
                        }



                    }
                }
            }
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field i : declaredFields) {
                i.setAccessible(true);
                if (name.equalsIgnoreCase(i.getName())) {
                    i.set(bean, value);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
